package com.sh.web.controller;

import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sh.bean.Resfood;
import com.sh.service.FileServiceBiz;
import com.sh.service.ResfoodBiz;
import com.sh.service.impl.FileServiceImpl;
import com.sh.utils.JwtTokenUtil;
import com.sh.web.model.JsonModel;
import com.sh.web.model.ResfoodVo;
import com.sh.web.models.MyPageBean;
import io.jsonwebtoken.Claims;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.constraints.Max;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

@RestController
@RequestMapping("resfood")   // 方便配置网关
@Slf4j
@RefreshScope  // nacos配置文件热部署
@Tag(name = "菜品查询API", description = "菜品管理的相关接口")
public class ResfoodController {

    @Autowired
    private ResfoodBiz resfoodBiz;

    @Autowired
    private FileServiceBiz fileServiceBiz;
    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Autowired
    private RedisTemplate redisTemplate;

    @Value("${res.data.shihao}")
    private String shi;

    // 查询菜品详情
    @GetMapping(value = "findById/{fid}")
    public Map<String, Object> findById(@PathVariable Integer fid) {
        System.out.println(shi);
        Map<String, Object> map = new HashMap<>();
        Resfood rf = null;
        try {
            rf = this.resfoodBiz.findById(fid);
        } catch (Exception e) {
            e.printStackTrace();
            map.put("code", 0);
            map.put("msg", "查询失败");
            return map;
        }
        map.put("code", 1);
        map.put("obj", rf);
        return map;
    }


    @GetMapping(value = "findAll")
    public JsonModel findAll() {
        JsonModel jm = new JsonModel();
        List<Resfood> list = null;
        try {
            list = this.resfoodBiz.findAll();
        } catch (Exception e) {
            e.printStackTrace();
            jm.setCode(0);
            jm.setError("查询失败");
            return jm;
        }
        jm.setCode(1);
        jm.setObj(list);
        return jm;
    }


    @Operation(summary = "分页查询", description = "分页查询")
    @ApiResponse(responseCode = "200", description = "查询成功",
            content = @Content(mediaType = "application/json", schema = @Schema(implementation = MyPageBean.class)))
    @PostMapping(value = "findByPage")  // 前端有请求实体，后端用post接收
    public Map<String, Object> findByPage(@RequestBody @Parameter(description = "分页查询实体") MyPageBean myPageBean) {
        Map<String, Object> map = new HashMap<>();
        Page<Resfood> page = null;
        page = this.resfoodBiz.findByPage(myPageBean.getPageno(),
                myPageBean.getPagesize(),
                myPageBean.getSortby(),
                myPageBean.getSort());
        map.put("code", 1);
        BeanUtils.copyProperties(page, myPageBean);
        myPageBean.calculate();  // 计算属性
        map.put("obj", myPageBean);
        return map;
    }


    @Operation(summary = "有条件的分页查询", description = "有条件的分页查询")
    @ApiResponse(responseCode = "200", description = "查询成功",
            content = @Content(mediaType = "application/json", schema = @Schema(implementation = MyPageBean.class)))
    @PostMapping(value = "findByPageWithCondition")  // 前端有请求实体，后端用post接收
    public Map<String, Object> findByPageWithCondition(@RequestBody @Parameter(description = "分页查询实体") MyPageBean myPageBean) {
        Map<String, Object> map = new HashMap<>();
        Page<Resfood> page = null;
        page = this.resfoodBiz.findFoods(myPageBean.getResfood(),
                myPageBean.getPageno(),
                myPageBean.getPagesize(),
                myPageBean.getSortby(),
                myPageBean.getSort());
        map.put("code", 1);
        BeanUtils.copyProperties(page, myPageBean);
        myPageBean.calculate();  // 计算属性
        map.put("obj", myPageBean);
        return map;
    }

    @Operation(summary = "添加菜品", description = "添加菜品")
    @ApiResponse(responseCode = "200", description = "添加成功",
            content = @Content(mediaType = "application/json",
                    schema = @Schema(implementation = ResfoodVo.class)))
    @PostMapping(value = "addResfood")
    public Map<String, Object> addResfood(@ModelAttribute ResfoodVo resfoodVo) throws ExecutionException, InterruptedException {
        String fphotoFilePath = "";
        CompletableFuture<String> fileUrlFuture = fileServiceBiz.upload(resfoodVo.getFphotofile());
        fphotoFilePath = fileUrlFuture.get();

        Resfood resfood = new Resfood();
        BeanUtils.copyProperties(resfoodVo, resfood);
        resfood.setFphoto(fphotoFilePath);
        Integer fid = this.resfoodBiz.addResfood(resfood);
        resfoodVo.setFid(fid);
        resfoodVo.setFphoto(fphotoFilePath);
        Map<String, Object> map = new HashMap<>();
        map.put("code", 1);
        map.put("obj", resfoodVo);
        return map;
    }


    // 点赞功能
    @GetMapping("/clickPraise/{fid}")
    public Map<String, Object> clickPraise(@PathVariable Integer fid, HttpServletRequest request) {
        Map<String, Object> map = new HashMap<>();
        String token = request.getHeader("token");
        Claims claims = jwtTokenUtil.decodeJWTWithKey(token);
        String userid = claims.get("userid").toString();
        if (this.redisTemplate.opsForSet().isMember("user_praise_fid:"+ userid, fid)){
//        if (this.redisTemplate.hasKey("user_praise_fid:"+ userid)){
            map.put("code", 0);
            map.put("msg", "您已经点过赞了");
            map.put("obj", this.redisTemplate.opsForValue().get("praise:"+fid));
            return map;
        }
        long praise = this.redisTemplate.opsForValue().increment("praise:" + fid);
        // 记录用户曾经点赞过的商品编号
        redisTemplate.opsForSet().add("user_praise_fid:"+ userid, fid);
        // 记录某个商品被哪些用户点赞过
        redisTemplate.opsForSet().add("fid_praise_user:"+fid, userid);
        map.put("code", 1);
        map.put("msg", "点赞成功");
        map.put("obj", praise);
        log.info("点赞返回的数据:{}", map);
        return map;
    }

    @GetMapping("/getPraise/{fid}")
    public Map<String, Object> getPraise(@PathVariable Integer fid) {
        Map<String, Object> map = new HashMap<>();
        map.put("code", 1);
        map.put("msg", "获取成功");
        map.put("obj", this.redisTemplate.opsForValue().get("praise:"+fid));
        return map;
    }

}
